package danny.hoi.web.controller.log;

import danny.hoi.domain.export.system.SysLog;
import danny.hoi.domain.export.system.User;
import danny.hoi.service.export.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;

    @Around("execution(* danny.hoi.web.controller..*.*(..))")
    public Object writeLog(ProceedingJoinPoint joinPoint) {
        SysLog sysLog = new SysLog();
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());
        }
        sysLog.setIp(request.getRemoteAddr());
        sysLog.setTime(new Date());
        sysLog.setMethod(joinPoint.getSignature().getName());
        sysLog.setAction(joinPoint.getTarget().getClass().getName());
        sysLogService.save(sysLog);
        try {
            Object proceed = joinPoint.proceed();
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
}
